﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using Plugins.Interfaces;

namespace Plugins.Threading
{
    public class PluginWorkItem<T> : IPluginWorkItem
    {
        private volatile int _dataCount = 0;
        private volatile bool _isRunAsync;
        private List<PluginThreadSafeStack<T>> _data;
        private BackgroundWorker _mainThread;
        private WaitHandle[] _waitHandles;
        protected void PushData(T item, int threadID)
        {
            if (_dataCount > 0)
            {
                _dataCount--;
            }
            _data[threadID].Push(item);
        }
        protected T PopData(int threadID)
        {
            return _data[threadID].Pop();
        }
        protected void PushData(T item)
        {
            lock (this)
            {
                if (_dataCount > 0)
                {
                    _dataCount--;
                }
                _data[GetMinIndex(GetThreadCount())].Push(item);
            }
        }
        protected int GetDataCount()
        {
            lock (this)
            {
                return _dataCount;
            }
        }
        protected T PopData()
        {
            lock (this)
            {
                return _data[GetMaxIndex(GetThreadCount())].Pop();
            }
        }
        private int GetThreadCount()
        {
            if (ThreadCount > 0 && ThreadCount < 64)
            {
                int threadCount = ThreadCount > Environment.ProcessorCount ? Environment.ProcessorCount : ThreadCount;
                return threadCount;
            }
            return 1;
        }
        protected virtual int ThreadCount { get { return Environment.ProcessorCount; } }
        protected virtual int DataCount { get { return 0; } }
        protected virtual void ProcessItem(int threadID)
        {
            int threadCount = GetThreadCount();
            bool useDataCount = DataCount > 0;
            T item;
            do
            {
                if (!IsRunAsync) return;
                item = PopData(threadID);
                if (item != null)
                {
                    if (!IsRunAsync) return;
                    ProcessData(item, threadID);
                }
            } while (!object.Equals(item, default(T)));
        }
        protected virtual void ProcessData(T item, int threadID) { }
        protected virtual void InitializeData() { }
        protected void InitializeThreadPoolData()
        {
            int threadCount = GetThreadCount();
            _dataCount = DataCount;
            T item = default(T);
            if (threadCount > 1)
            {
                int count = threadCount;
                int loop = 0;
                for (; loop < count; )
                {
                    while (_data[loop].Count == 0 && count > 1)
                    {
                        count--;
                    }
                    loop++;
                }
                if (count < threadCount)
                {
                    item = PopData(0);

                    for (int i = 0; (i + 1) < threadCount && !object.Equals(item, default(T)); )
                    {
                        int offset = 0;
                        do
                        {
                            ProcessData(item, i + offset + 1);
                            item = PopData(GetMaxIndex(i + offset + 2));
                            offset++;
                        }
                        while ((i + offset + 1) < threadCount && !object.Equals(item, default(T)));
                        count = i + offset + 1;
                        loop = 0;
                        for (; loop < count; )
                        {
                            while (_data[loop].Count == 0 && count > 1)
                            {
                                _data.RemoveAt(loop);
                                _data.Add(new PluginThreadSafeStack<T>());
                                count--;
                            }
                            loop++;
                        }
                        if (count == threadCount)
                        {
                            break;
                        }
                        item = PopData(GetMaxIndex(loop));
                        i = count - 1;
                    }
                }
            }
            for (int i = 0; i < threadCount - 1; i++)
            {
                if (_data[i + 1].Count > 0 && _data[i].Count == 0)
                {
                    throw new InvalidProgramException();
                }
            }
        }
        public event EventHandler<EventArgs> Start;
        public event EventHandler<EventArgs> Stop;
        private void OnStart()
        {
            if (Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }
        private void OnStop()
        {
            if (Stop != null) 
            {
                Stop(this, EventArgs.Empty);
            }
        }
        protected void RunAsync()
        {
            InitializeThreadPool();
            InitializeData();
            InitializeThreadPoolData();
            int threadCount = GetThreadCount();
            for (int i = 0; i < threadCount; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessHandle), i);
            }
            WaitHandle.WaitAll(_waitHandles);
        }
        protected void Run()
        {
            InitializeThreadPool();
            InitializeData();
            int threadCount = GetThreadCount();
            _isRunAsync = true;
            for (int i = 0; i < threadCount; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessHandle), i);
            }
            WaitHandle.WaitAll(_waitHandles);
            _isRunAsync = false;
        }
        private void InitializeThreadPool()
        {
            int threadCount = GetThreadCount();
            this._waitHandles = new WaitHandle[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                _waitHandles[i] = new AutoResetEvent(false);
            }
            this._data = new List<PluginThreadSafeStack<T>>(threadCount);
            for (int i = 0; i < threadCount; i++)
            {
                _data.Add(new PluginThreadSafeStack<T>());
            }
        }
        private int GetMaxIndex(int index)
        {
            int max = 0;
            int maxIndex = 0;
            for (int i = 0; i < index; i++)
            {
                if (_data[i].Count > max)
                {
                    max = _data[i].Count;
                    maxIndex = i;
                }
            }
            return maxIndex;
        }
        private int GetMinIndex(int index)
        {
            int min = int.MaxValue;
            int minIndex = 0;
            for (int i = 0; i < index; i++)
            {
                if (_data[i].Count < min)
                {
                    min = _data[i].Count;
                    minIndex = i;
                }
            }
            return minIndex;
        }
        private void ProcessHandle(object sync)
        {
            int threadID = (int)sync;
            AutoResetEvent waitHandle = (AutoResetEvent)_waitHandles[threadID];
            ProcessItem(threadID);
            waitHandle.Set();
        }
        protected bool IsRunAsync
        {
            get
            {
                return _isRunAsync;
            }
        }
        #region IWorkItem Members
        void IPluginWorkItem.Run()
        {
            lock (this)
            {
                Run();
            }
        }
        void IPluginWorkItem.RunAsync()
        {
            lock (this)
            {
                if (!_isRunAsync)
                {
                    Initialize();
                    _mainThread.DoWork += (object sender, DoWorkEventArgs e) => { RunAsync(); };
                    _mainThread.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => { Terminate(); };
                    _mainThread.WorkerSupportsCancellation = true;
                    _mainThread.RunWorkerAsync();
                }
            }
        }
        void IPluginWorkItem.CancelAsync()
        {
            lock (this)
            {
                if (_isRunAsync)
                {
                    _mainThread.CancelAsync();
                    _isRunAsync = false;
                    Terminate();
                }
            }
        }
        protected virtual void Initialize()
        {
            lock (this)
            {
                if (_mainThread == null)
                {
                    _mainThread = new BackgroundWorker();
                    _isRunAsync = true;
                    OnStart();
                }
            }
        }
        protected virtual void Terminate()
        {
            lock (this)
            {
                if (_mainThread != null)
                {
                    OnStop();
                    _mainThread = null;
                    _isRunAsync = false;
                }
            }
        }   
        bool IPluginWorkItem.IsRunAsync
        {
            get
            {
                return _isRunAsync;
            }
        }
        #endregion
    }
}
